package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/treasure/configuration"
	"kop/modules/treasure/entity"
	"kop/pb"
)

func GetGrades(dB *gorm.DB, roleID int32) []*pb.TreasureGrade {

	var res []entity.TreasureGrade
	if err := dB.Where("role_id = ?", roleID).Find(&res).Error; err != nil {
		panic(err)
	}

	var points = make([]*pb.TreasureGrade, 0, len(res)+1)
	for _, p := range res {

		points = append(points, buildPbGrade(p))
	}

	return points
}

func GetGrade(dB *gorm.DB, roleID, mapID int32) *pb.TreasureGrade {

	var p = entity.TreasureGrade{
		RoleID: roleID,
		MapID:  mapID,
	}

	if err := dB.FirstOrCreate(&p).Error; err != nil {
		panic(err)
	}

	return buildPbGrade(p)
}

func SaveGrade(dB *gorm.DB, roleID int32, point *pb.TreasureGrade) {

	var p = entity.TreasureGrade{
		RoleID: roleID,
		MapID:  point.MapID,
		Grade:  point.Grade,
	}
	if err := dB.Save(&p).Error; err != nil {
		panic(err)
	}

	*point = *(buildPbGrade(p))
}

func buildPbGrade(p entity.TreasureGrade) *pb.TreasureGrade {

	var conf, err = configuration.GetTreasureByMapID(p.MapID)
	if err != nil {
		panic(err)
	}

	var point = pb.TreasureGrade{
		MapID:   p.MapID,
		Grade:   p.Grade,
		AwardID: conf.AwardID,
	}

	return &point
}
